package com.laoli.lab39;

import java.util.Random;
import java.util.concurrent.CompletableFuture;

/**
 * exceptionally()与 handle() 线程使用示例
 */
public class UseThread {
    public static void main(String[] args) throws InterruptedException {
        // 异步任务
        CompletableFuture<Object> task = CompletableFuture.supplyAsync(() -> {
                    //return new Random().nextInt(10) + 1;
                    /*try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }*/
            // 如果下面handle和exceptionally不加async后缀，并且这里进行休眠（也就是相当于耗时操作），那就不是用主线程，而是用异步线程执行，如果不休眠了（没有耗时操作），那就是用主线程！
                    throw new RuntimeException("taskAException");
                })
                .handleAsync((result, exception) -> {
                    System.out.printf("【handle】线程名称：%s \n", Thread.currentThread().getName());
                    if(exception!=null){
                        throw new RuntimeException(exception.getCause().getMessage());
                    }
                    return result;
                })
                .exceptionallyAsync(exception -> {
                    System.out.printf("【exceptionally】线程名称：%s \n", Thread.currentThread().getName());
                    return 0;
                });
        // 主线程休眠
        Thread.sleep(5000);
    }
}
